import React,{useState, useEffect} from 'react'
import { useNavigate } from 'react-router-dom'
import { Sticky } from '@nutui/nutui-react'
import './xxy.css'
import '@nutui/nutui-react/dist/style.css'
import axios from 'axios'
import { Card, Toast, Button,InfiniteScroll, List,DotLoading } from 'antd-mobile'
import { Cart,TriangleUp,TriangleDown,Filter } from '@nutui/icons-react'
import { SearchBar } from '@nutui/nutui-react'

export default function Home() {
  let [goods, setGoods] = useState([])
  let [goodtypes, setGoodtypes] = useState([])
  let [activeIndex, setActiveIndex] = useState('66d4542863562b60074a24bf')
  let [sorttype,setSortType]= useState(0)
  const Navigate = useNavigate()
  const [value, setValue] = useState('')
  const [carts, setCarts] = useState([])
  const [uid, setUid] = useState('66d458f9fcde96eddecc55cc')
  const getCart = () => {
    axios.get(`/XXY/getcart?uid=${uid}`).then(res => {
      let cartlist= res.data.data[0].goodslist
      setCarts(cartlist)
    })
  }
  const gogood = (item) => {
    console.log(item)
    Navigate('/Detailsxxy',{state:item})
  }
  const getGoodtypes = () => {
    axios.get('/XXY/goodstype').then(res => {
      if(res.data.code == 200) {
        setGoodtypes(res.data.data)
      }
    })
  }
  const getGoods = (val) => {
    if(val) {
      if(activeIndex=='66d4542863562b60074a24bf'){
        axios.get(`/XXY/goods?val=${val}`).then(res => {
          if(res.data.code === 200) {
            setGoods(res.data.data)
          }
        })
      }else {
        axios.get(`/XXY/goods?type=${activeIndex}&&val=${val}`).then(res => {
          if(res.data.code === 200) {
            setGoods(res.data.data)
          }
        })
      }
    }else{
      if(activeIndex=='66d4542863562b60074a24bf'){
        axios.get(`/XXY/goods`).then(res => {
          if(res.data.code === 200) {
            setGoods(res.data.data)
          }
        })
      }else {
        axios.get(`/XXY/goods?type=${activeIndex}`).then(res => {
          if(res.data.code === 200) {
            setGoods(res.data.data)
          }
        })
      }
    }
  }
  const newgoods = (typeid)=>{
    let newgood = [...goods]
    let a = sorttype
    if(sorttype==0){
      newgood= [...goods]
    }else if(sorttype==1){
      newgood= newgood.sort((a,b)=>a.price-b.price)
    }else if(sorttype==2){
      newgood= newgood.sort((a,b)=>b.soldnum-a.soldnum)
    }else if(sorttype==3){
      newgood= newgood.filter((a)=>a.isjx==1)
    }
    return newgood
  }
  useEffect(() => {
    getGoodtypes()
    getGoods()
    getCart()
  },[])

  const changeActiveIndex = (index) => {
    setActiveIndex(index)
  }
  useEffect(() => {  
    getGoods();  
  }, [activeIndex])
  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span></span>
            <DotLoading color='rgb(0,204,153)' />
          </>
        ) : (
          <span style={{color:'#999'}}>--- 没有更多商品了 ---</span>
        )}
      </>
    )
  }
  const [hasMore, setHasMore] = useState(true)
  const [len , setLen] = useState(4)
  async function loadMore() {
    setTimeout(() => {
      setLen(len + 4)
      setHasMore(len<goods.length)
    },2000)
  }
  return (
    <div className='xxyhome'>
      <div className='xxyhome_top'>
        
      </div>
      <div className='xxyhome_search'>
      <Sticky threshold={0} style={{width: '100%'}}>
        <SearchBar  onChange={(val) => setValue(val)}
        onSearch={(val) => {getGoods(val)}}
        style={{'--nutui-searchbar-background':'#fff'}} shape="round" placeholder='搜索药品' rightIn={
        <div>
          <span>| </span>
          <span style={{'color':'black'}}>&nbsp; 搜索</span>
        </div>
      }
      right={
        <div className='search_right'>
        <Cart width={20} height={20} onClick={() => {
          Navigate('/Cartxxy')
        }
        }/>
        <span className='cartCount'>{carts.length}</span>
        </div>
      }
      />
      </Sticky>
      </div>
      <div className='xxyhome_banner'>
        {goodtypes.map((item,index)=>{
          return(
          <div className={item._id==activeIndex?'banner_item_active':'banner_item'} key={index} onClick={()=>{
            changeActiveIndex(item._id)
          }}>
            <img src={item.src} alt="" />
            <p>{item.title}</p>
          </div>
          )
        })}
      </div>
      <div className='xxyhome_list'>
        <div className='list_sort'>
          <div className='sort_item'>
            <span style={{color:sorttype==0?'rgb(81, 203, 81)':'#888888'}} onClick={()=>{
              setSortType(0)
              newgoods(0)
            }
            } >综合</span>
            <span style={{color:sorttype==1?'rgb(81, 203, 81)':'#888888'}} onClick={()=>{
              setSortType(1)
              newgoods(1)
            }
            } >销量
            <div className='arr'>
              <TriangleUp width={10} className='up' color='#ccc'/>
              <TriangleDown width={10} className='down' color='#ccc'/>
            </div>
            </span>
            <span style={{color:sorttype==2?'rgb(81, 203, 81)':'#888888'}} onClick={()=>{
              setSortType(2)
              newgoods(2)
            }
            } >价格
            <div className='arr'>
              <TriangleUp width={10} className='up' color='#ccc'/>
              <TriangleDown width={10} className='down' color='#ccc'/>
            </div>
            </span>
          </div>
          <div className='sort_item'>
            <span style={{color:sorttype==3?'rgb(81, 203, 81)':'#888888'}} onClick={()=>{
              setSortType(3)
              newgoods(3)
            }
            } >仅看有货</span>
            <span  style={{color:sorttype==4?'rgb(81, 203, 81)':'#888888'}} onClick={()=>{
              setSortType(4)
              newgoods(4)
            }
            } >
            <Filter width='14' style={{marginRight: '5px'}} color='#BBB' />
              筛选
            </span>
          </div>
        </div>
        <div className='list_goods'>
          {newgoods().slice(0,len).map(item => {
            return (
              <Card  className='goods_item' key={item._id} onClick={()=>{gogood(item)}}>
                <img src={item.img} alt="" />
                <div className='goods_info'>
                  <p>{item.name.length>=21?item.name.slice(0,21)+'...':item.name}</p>
                  <p style={{fontSize:'13px',color:'#ccc',margin:'9px 0'}} className='price'><s>{item.price%1==0?item.price+'.00':(item.price%0.1?item.price+'0':item.price)}</s></p>
                  <div className='goods_group'>
                    <p>￥{item.discount%1==0?item.discount+'.00':(item.discount%0.1?item.discount+'0':item.discount)}</p>
                    <button>购买</button>
                  </div>
                </div>
              </Card>
          )
          }
          )}
        </div>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </div>
    </div>
  )
}
